package com.kaci.springbootormlite.component;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.jdbc.JdbcConnectionSource;
import com.j256.ormlite.jdbc.JdbcPooledConnectionSource;
import com.j256.ormlite.jdbc.db.MysqlDatabaseType;
import com.j256.ormlite.table.TableUtils;
import com.kaci.springbootormlite.entity.User;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.sql.SQLException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class DatabaseHelper {
    private static final String DATABASE_URL = "jdbc:mysql://localhost:3308/db_localserver?autoReconnect=true&connectTimeout=30000&socketTimeout=30000&useUnicode=true&connectTimeout=30000&socketTimeout=30000&characterEncoding=utf8&useAffectedRows=true&allowMultiQueries=true&useSSL=false&allowPublicKeyRetrieval=true&sessionVariables=sql_mode='STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'";

    private JdbcPooledConnectionSource connectionSource;
    private Dao<User, Integer> userDao;
    public  static  ExecutorService executorService = Executors.newFixedThreadPool(10);
    @PostConstruct
    public void init() throws SQLException {
        connectionSource = new JdbcPooledConnectionSource(DATABASE_URL,"root","kacidev");
        connectionSource.setMaxConnectionsFree(50);
        connectionSource.setDatabaseType(new MysqlDatabaseType());
        // maximum age that a connection can be before being closed
        connectionSource.setMaxConnectionAgeMillis(300);
        //获取连接前，验证连接是否可用
        connectionSource.setTestBeforeGet(true);
        userDao = DaoManager.createDao(connectionSource, User.class);
        // 创建表（如果不存在）
        TableUtils.createTableIfNotExists(connectionSource, User.class);
    }

    public Dao<User, Integer> getUserDao() {
        return userDao;
    }

    @PreDestroy
    public void close() throws Exception {
        connectionSource.close();
    }
}